package com.bw.cart.service.impl;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.cart.mapper.CartMapper;
import com.bw.cart.service.CartService;
import com.bw.common.redis.service.RedisService;
import com.bw.common.security.service.TokenService;

import com.bw.common.security.utils.SecurityUtils;
import com.bw.constant.CartConstant;

import com.bw.constant.domain.dto.CartDto;
import com.bw.domain.*;
import com.bw.domain.vo.CartItem;
import com.bw.domain.vo.CartVo;
import com.bw.domain.vo.DiscountCouponVo;
import com.bw.model.LoginUser;

import io.swagger.v3.core.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private RedisService redisService;


    @Override
    public void insert(Long skuId, Long num) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserid();
        String userCart = CartConstant.User_CART + userId;
        //根据用户id去查商户id
        Shop shop= cartMapper.findByShopId(userId);
        if (!redisService.hasKey(userCart)){
            Cart cartInfo = getInfoBySkuId(skuId);
            if (cartInfo == null){
                //没有查到数据，就存入redis，否则会击穿
                redisService.setCacheMap(userCart,null);
            }
        }
        //从redis取出购物车对象
        Object cacheMapValue = redisService.getCacheMapValue(userCart,skuId.toString());
        CartItem cartItem = JSON.parseObject(JSONObject.toJSONString(cacheMapValue), CartItem.class);
        //购物车详情判断
        if (cartItem == null){
            cartItem = createCartItem(skuId,num);
        }

        if (cartItem.getNum() > 200){
            throw new RuntimeException("不能超过200");
        }

        cartItem.setNum(num);
        redisService.setCacheMapValue(userCart, skuId.toString(), cartItem);
    }

    /**
     * 结算页面
     * @param settlementParameters
     * @return
     */
    @Override
    public List<PmsSkuInfo> settlementList(SettlementParameter settlementParameters) {

        List<PmsSkuInfo> list = new ArrayList<>();
        settlementParameters.getSkuIds().forEach(skuId->{
            //查询商品信息
            PmsSkuInfo pmsSkuInfo = cartMapper.selectSku(skuId);

            list.add(pmsSkuInfo);
        });

        return list;
    }

    /**
     * 商品对应的优惠卷列表
     * @param skuId
     * @return
     */
    @Override
    public List<DiscountCoupon> couponBySettlementId(Long skuId) {
        //查询商品下的优惠卷
        List<DiscountCoupon> discountCoupon = cartMapper.selectDiscountCoupon(skuId);
        return discountCoupon;
    }

    /**
     * 商品购买数量
     * @param changeNum
     */
    @Override
    public void changeNum(ChangeNum changeNum) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserid();
        String userCart = CartConstant.User_CART + userId;
        //查询redis商品信息
        PmsSkuInfo cacheMapValue = redisService.getCacheMapValue(userCart,changeNum.getSkuId().toString());
        cacheMapValue.setNum(changeNum.getNum());
        //更新redis
        redisService.setCacheMapValue(userCart, changeNum.getSkuId().toString(), cacheMapValue);
    }

    /**
     * 优惠卷结算
     * @param couponParameter
     * @return
     */
    @Override
    public BigDecimal couponSettlement(CouponParameter couponParameter) {
        DiscountCouponVo discountCoupon = cartMapper.selectCouponBySkuId(couponParameter.getCouponId());
        CoupinType coupinType = cartMapper.selectCatrType(discountCoupon.getCouponType());
        PmsSkuInfo pmsSkuInfo = cartMapper.selectSkuInfoBySkuId(couponParameter.getSkuId());
        //满减券
        if (discountCoupon.getTypeId() == 1){
            couponParameter.setSumMoney(pmsSkuInfo.getPrice().subtract(BigDecimal.valueOf(coupinType.getValue())));
            return couponParameter.getSumMoney();
        }
        //满额卷
        if (discountCoupon.getTypeId() == 2){
            couponParameter.setSumMoney(pmsSkuInfo.getPrice().multiply(BigDecimal.valueOf(coupinType.getValue()/100)));
            return couponParameter.getSumMoney();
        }
        //随机卷
        if(discountCoupon.getTypeId() == 3){
            BigDecimal num = BigDecimal.valueOf(new Random().nextInt(coupinType.getValue()) + coupinType.getValue2());
            couponParameter.setSumMoney(num);
            return couponParameter.getSumMoney();
        }
        return couponParameter.getSumMoney();
    }


    protected CartItem createCartItem(Long skuId,Long num){

        CartItem cartItem = new CartItem();
        PmsSkuInfo pmsSkuInfo = cartMapper.selectSkuInfoBySkuId(skuId);
        //根据skuid,去查询他下面优惠券
        List<DiscountCoupon>discountCouponList=cartMapper.selectCouponByShopId(skuId);
        //赋值
        cartItem.setSkuId(skuId);
        cartItem.setShopId(pmsSkuInfo.getSpuId());
        cartItem.setSkuName(pmsSkuInfo.getSkuName());
        cartItem.setNum(Long.valueOf(num));
        cartItem.setChecked(Long.valueOf(0));
        cartItem.setPrice(pmsSkuInfo.getPrice());
        cartItem.setShopName(pmsSkuInfo.getShopName());
        cartItem.setSkuImg(pmsSkuInfo.getSkuDefaultImg());
        cartItem.setSkuTitle(pmsSkuInfo.getSkuTitle());
        cartItem.setDiscountCouponList(discountCouponList);
        return cartItem;
    }
    protected Cart getInfoBySkuId(Long skuId){
        Cart cartItems = cartMapper.selectCartItemBySKuId(skuId);
        return cartItems;
    }

    @Override
    public List<CartVo> selectCartList(Long userid) {
        //去redis取
        Map<String, Object> cacheMap = redisService.getCacheMap(CartConstant.User_CART + 1);
        //转换
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(cacheMap));
        Set<String> keys = jsonObject.keySet();
        List<CartItem> cartItemList = new ArrayList<>();
        for (String key : keys) {
            CartItem cartItem = jsonObject.getObject(key, CartItem.class);
            //取出优惠券列表
            List<DiscountCoupon> discountCouponList = cartItem.getDiscountCouponList();
            //循环
            discountCouponList.forEach(couponId->{
                //根据优惠券id查询每个商品下对应的优惠券
                List<CoupinType>coupinTypeList = cartMapper.findByCouponId(couponId.getCouponId());
                //将查出来的优惠券集合存入
                couponId.setCoupinTypeList(coupinTypeList);
            });
            cartItemList.add(cartItem);
        }
        List<CartVo> cartVos = new ArrayList<>();
        List<CartVo> cartVoList = convertToListOfCartVo(cartItemList);
        cartVoList.forEach(cartVo->{
            cartVo.getCartItemList().forEach(item->{
                System.out.println(item.getNum());
            });
            cartVos.add(cartVo);
        });
        return cartVos;

    }



    public static List<CartVo> convertToListOfCartVo(List<CartItem> cartItemList) {
        Map<Long, List<CartItem>> groupedBySellerId = cartItemList.stream()
                .collect(Collectors.groupingBy(CartItem::getShopId));

        List<CartVo> cartVoList = new ArrayList<>();

        for (Map.Entry<Long, List<CartItem>> entry : groupedBySellerId.entrySet()) {
            Long sellerId = entry.getKey();
            List<CartItem> items = entry.getValue();

            String sellerName = items.get(0).getShopName();

            CartVo cartVo = new CartVo();
            cartVo.setShopId(sellerId);
            cartVo.setShopName(sellerName);
            cartVo.setCartItemList(items);

            cartVoList.add(cartVo);
        }

        return cartVoList;
    }

}
